package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.article.ArticleConstants;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.constants.message.PublishArticleConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @作者 itcast
 * @创建日期 2021/9/23 10:15
 **/
@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Value("${file.oss.endpoint}")
    String endpoint;

    @Value("${file.oss.access-key-id}")
    String accessKeyId;

    @Value("${file.oss.access-key-secret}")
    String accessKeySecret;

    @Value("${file.oss.bucket-name}")
    String bucketName;

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 自媒体文章人工审核
     *
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // 通知定时发布文章
        if (WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)) {
            //5. 通知定时发布文章
            // 发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            // 当前时间
            long nowTime = new Date().getTime();
            long remainTime = publishTime - nowTime;
            if (remainTime <= 0) {
                // 立即发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                        , wmNews.getId()
                );
                log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
            } else {
                // 延时发布
                rabbitTemplate.convertAndSend(PublishArticleConstants.PUBLISH_ARTICLE_EXCHANGE
                        , PublishArticleConstants.PUBLISH_ARTICLE_DEAD_ROUTE_KEY
                        , wmNews.getId()
                        , (message) -> {
                            message.getMessageProperties().setExpiration(String.valueOf(remainTime));
                            return message;
                        }
                );
                log.info("延时发布文章通知成功发送，文章id : {} , 延时时间: {}毫秒", wmNews.getId(), remainTime);
            }
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        // 1. 检查参数  检查分页
        dto.checkParam();
        //  检查是否登录用户
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2. 封装查询条件
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        //  2.1 分页条件
        IPage<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        //  2.2 关键字   like == 标题
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //  2.3 频道    eq == 频道id
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //  2.4 状态    eq
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //  2.5 大于等于 开始时间
        queryWrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        //  小于等于 结束时间
        queryWrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        //  2.6 用户过滤条件   eq == user_id
        queryWrapper.eq(WmNews::getUserId, user.getId());
        //  2.7 时间降序
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        // 3.执行查询
        IPage<WmNews> pageResult = this.page(pageReq, queryWrapper);
        // 4.封装结果
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        responseResult.setData(pageResult.getRecords());
        //  host设置访问前缀
        responseResult.setHost(webSite);
        return responseResult;
    }


    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1. 检查封装参数
        if (StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        Short status = dto.getStatus();
        if (!WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status) && !WemediaConstants.WM_NEWS_SUMMIT_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章状态错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "请先登录");
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        // type == -1  暂时设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);
        }
        // 封面  list  == String
        List<String> coverList = dto.getImages();
        if (CollectionUtils.isNotEmpty(coverList)) {
            wmNews.setImages(imageListToStr(coverList));
        }
        // 登录用户
        wmNews.setUserId(user.getId());

        // 2. 保存或修改文章
        saveOrUpdateWmNews(wmNews);
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(status)) {
            return ResponseResult.okResult();
        }
        // 3 保存素材 和 文章的关联关系
        // 3.1 抽取内容中所有的图片url路径
        List<String> imageList = parseContentImages(wmNews.getContent());
        // 3.2 保存文章内容和素材的关联关系
        if (CollectionUtils.isNotEmpty(imageList)) {
            //  引用的素材url路径列表   文章id         引用类型
            saveRelativeInfo(imageList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        // 3.2 保存文章封面和素材的关联关系
        saveRelativeInfoForCover(dto, wmNews, imageList);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("成功发送 待审核消息 ==> 队列:{}, 文章id:{}", NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());

        //获取关联的article 的id
        Long articleId = wmNews.getArticleId();
        //远程调用
        ResponseResult<ApArticle> article = articleFeign.findArticle(articleId);
        //判断是否为空
        if (article != null) {
            //mq同步
            //1.同步修改自媒体文章is_delete
            rabbitTemplate.convertAndSend(ArticleConstants.ARTICLE_DELETE_FOR_ARTICLECONFIG_QUEUE, articleId
            );
            //2.同步删除对应的静态页
            rabbitTemplate.convertAndSend(ArticleConstants.ARTICLE_DELETE_FOR_MINIO_QUEUE, articleId
            );
            //3.同步删除索引库中对应的文章数据
            rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE, articleId
            );
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        //1.检查参数
        if (dto == null || dto.getId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        //4.修改文章状态，同步到app端（后期做）
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId())
                .set(WmNews::getEnable, dto.getEnable()));
        // 发送上下架消息
        if (wmNews.getArticleId() != null) {
            if (enable.equals(WemediaConstants.WM_NEWS_UP)) {
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY, wmNews.getArticleId());

                // 同步索引库
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE, wmNews.getArticleId());

                log.info("文章上架消息发送成功  文章的id : {}", wmNews.getArticleId());
            } else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY, wmNews.getArticleId());

                // 同步索引库
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE, wmNews.getArticleId());

                log.info("文章下架消息发送成功  文章的id : {}", wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    WmNewsMapper wmNewsMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%" + dto.getTitle() + "%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    /**
     * 生成封面内容  并 保存封面和素材的关联关系
     *
     * @param dto
     * @param wmNews
     * @param imageList
     */
    private void saveRelativeInfoForCover(WmNewsDTO dto, WmNews wmNews, List<String> imageList) {
        // 1. 入参中封面集合属性
        List<String> images = dto.getImages();

        //压缩图片新集合
        List<String> zipImages = new ArrayList<>();

        // 2. 如果type为-1 代表要根据内容图片集合  自动生成封面
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) { // -1
            // 2.1 集合数量大于2多图   wmNews设置为3   在内容图片集合中 解析前3张图片作为封面
            if (imageList.size() > 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = imageList.stream().limit(3).collect(Collectors.toList());
            } else if (imageList.size() > 0 && imageList.size() <= 2) {
                // 2.2 集合数量大于0  小于等于2  wmNews设置为1  在内容图片集合中 解析前1张图片作为封面
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = imageList.stream().limit(1).collect(Collectors.toList());
            } else {
                // 2.3 设置为无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            }
            if (CollectionUtils.isNotEmpty(images)) {
                for (String image : images) {
                    //内容图片无webSite,url链接会失败，url需识别http
                    image = webSite + image;
                    zipAndUpImagesToOss(zipImages, image);
                }
                // 如果自动生成的封面不为空 ， 将集合转为字符串拼接
                wmNews.setImages(imageListToStr(zipImages));
                updateById(wmNews); // 修改wmNews
            }

        } else {
            for (String image : images) {
                zipAndUpImagesToOss(zipImages, image);
            }
            wmNews.setImages(imageListToStr(zipImages));
            updateById(wmNews); // 修改wmNews
        }
        // 判断最终封面集合是否为空
        if (CollectionUtils.isNotEmpty(images)) {
            images = images.stream().map(url -> url.replaceAll(webSite, "")).collect(Collectors.toList());

            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);// 保存封面和素材的关联关系
        }
    }

    private void zipAndUpImagesToOss(List<String> zipImages, String image) {
        //构造url
        try {
            //将字符串转换为url,内容中的图片没http，需添加
            URL url2 = new URL(image);
            URLConnection con2 = url2.openConnection();
            con2.setConnectTimeout(5 * 1000);
            //得到输入流
            InputStream inputStream1 = con2.getInputStream();
            String suffix2 = image.substring(image.lastIndexOf(".") + 1);
            //压缩后的BufferedImage
            BufferedImage bufferedImage2 = Thumbnails.of(inputStream1).size(256, 256).keepAspectRatio(false).asBufferedImage();
            //上传阿里云
            ByteArrayOutputStream os2 = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage2, suffix2, os2);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(os2.toByteArray());
            OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //删除http..
            String imageUrl2 = org.apache.commons.lang3.StringUtils.remove(image, webSite);
            //删除后缀名
            String noSuffix2 = org.apache.commons.lang3.StringUtils.remove(imageUrl2, suffix2);
            //
            String noSuffix3 = org.apache.commons.lang3.StringUtils.remove(noSuffix2, ".");
            String neimgUrl = noSuffix2 + "new." + suffix2;
            image = neimgUrl;
            zipImages.add(image);
            client.putObject(bucketName, image, inputStream);
            client.shutdown();
            log.info("文件压缩上传成功");

        } catch (IOException e) {
            e.printStackTrace();
            log.error("文件压缩上传失败.......");
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * @param imageList select * from wm_material where url in (url1  , url2  , url3 ) and user_id = ?
     * @param newsId
     * @param type
     */
    private void saveRelativeInfo(List<String> imageList, Integer newsId, Short type) {
        // 1. 根据素材url列表+登录人ID  查询出对应的素材列表
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery()
                .in(WmMaterial::getUrl, imageList).eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId()));
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的素材信息不存在");
        }
        // 2. 将得到的素材列表转化成map   key: 素材url     value: id
        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        // 3. 遍历 imageList 素材列表，判断每一个素材是否存在  ，  收集id到集合中
        List<Integer> materialIds = new ArrayList<>();
        for (String materialUrl : imageList) {
            if (!urlAndIdMap.containsKey(materialUrl)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "关联的素材信息不存在");
            }
            materialIds.add(urlAndIdMap.get(materialUrl));
        }
        // 4. 调用mapper的批量插入方法，保存关联关系
        wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);
    }

    /**
     * 抽取内容中所有图片
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        //  "[ {type: "image", value: "图片url"},{} ]"
        // 1. 将内容json字符串转化为 List<Map> 集合
        List<Map> mapList = JSONArray.parseArray(content, Map.class);
        // 过滤 type=image对应数据
        return mapList.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value")) // 获取数据中的value部分  : 图片url路径
                .map(url -> url.replaceAll(webSite, ""))// 去除路径前缀
                .collect(Collectors.toList()); // 将数据收集到集合
    }


    /**
     * 保存或修改
     *
     * @param wmNews
     */
    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setSubmitedTime(new Date());
        if (wmNews.getId() == null) {
            // 保存
            wmNews.setCreatedTime(new Date());
            save(wmNews);
        } else {
            // 修改
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     * 将图片集合  转化为 字符串   多个图片 用 逗号拼接  要图片路径的前缀去除
     *
     * @param coverList
     * @return
     */
    private String imageListToStr(List<String> coverList) {
        // 去除前缀路径 webSite
        return coverList.stream().map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.joining(",")); // 使用逗号拼接成字符串
    }


    @Autowired
    WmUserMapper wmUserMapper;

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVo);
        if (wmUser != null) {
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }
}
